<template>
  <div class="wms-receipt-order-page art-full-height">
    <!-- 搜索栏 -->
    <WmsReceiptOrderSearch
      v-model:filter="searchFilter"
      @search="handleSearch"
      @reset="handleReset"
    />

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格工具栏 -->
      <ArtTableHeader
        v-model:columns="columnChecks"
        @refresh="refreshData"
        layout="refresh,size,fullscreen,columns,settings"
      >
        <template #left>
          <ElButton type="primary" @click="showDialog('add')" v-ripple>
            <ElIcon><Plus /></ElIcon>
            新增入库单
          </ElButton>
          <ElButton @click="handleBatchProcess" v-ripple>
            <ElIcon><Operation /></ElIcon>
            批量处理
          </ElButton>
          <ElButton @click="handleExport" v-ripple>
            <ElIcon><Download /></ElIcon>
            导出
          </ElButton>
          <ElButton @click="handlePrint" v-ripple>
            <ElIcon><Printer /></ElIcon>
            打印
          </ElButton>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="isLoading"
        :data="tableData"
        :columns="columns"
        :pagination="paginationState"
        @selection-change="handleSelectionChange"
        @pagination:size-change="onPageSizeChange"
        @pagination:current-change="onCurrentPageChange"
        @expand-change="handleExpandChange"
      >
        <!-- 自定义列插槽 -->
        <template #orderInfo="{ row }">
          <div class="order-info">
            <div class="order-no">{{ row.receiptOrderNo }}</div>
            <div class="order-type">
              <ElTag :type="getOrderTypeTagType(row.receiptOrderType)">
                {{ getOrderTypeName(row.receiptOrderType) }}
              </ElTag>
            </div>
          </div>
        </template>

        <template #warehouseInfo="{ row }">
          <div class="warehouse-info">
            <div class="warehouse-name">{{ row.warehouseName }}</div>
            <div class="area-name" v-if="row.areaName">{{ row.areaName }}</div>
          </div>
        </template>

        <template #merchantInfo="{ row }">
          <div class="merchant-info" v-if="row.merchantName">
            <ElTag type="info">{{ row.merchantName }}</ElTag>
          </div>
          <span v-else class="text-placeholder">-</span>
        </template>

        <template #statusInfo="{ row }">
          <ElTag :type="getStatusTagType(row.receiptOrderStatus)">
            {{ getStatusName(row.receiptOrderStatus) }}
          </ElTag>
        </template>

        <template #amountInfo="{ row }">
          <div class="amount-info">
            <div class="total-amount">
              <ElStatistic
                :value="row.totalAmount || 0"
                :precision="2"
                prefix="¥"
              />
            </div>
            <div class="item-count">
              <ElText size="small" type="info">
                {{ row.totalQuantity || 0 }} 件商品
              </ElText>
            </div>
          </div>
        </template>

        <template #actions="{ row }">
          <ElButton type="primary" link @click="handleView(row)">
            <ElIcon><View /></ElIcon>
            查看
          </ElButton>
          <ElButton
            type="warning"
            link
            @click="handleEdit(row)"
            v-if="canEdit(row)"
          >
            <ElIcon><Edit /></ElIcon>
            编辑
          </ElButton>
          <ElButton
            type="success"
            link
            @click="handleProcess(row)"
            v-if="canProcess(row)"
          >
            <ElIcon><Check /></ElIcon>
            处理
          </ElButton>
          <ElButton
            type="danger"
            link
            @click="handleDelete(row)"
            v-if="canDelete(row)"
          >
            <ElIcon><Delete /></ElIcon>
            删除
          </ElButton>
        </template>

        <!-- 展开行内容 -->
        <template #expand="{ row }">
          <WmsReceiptOrderDetail
            :order-id="row.id"
            :loading="detailLoadingMap[row.id]"
            @loaded="handleDetailLoaded"
          />
        </template>
      </ArtTable>
    </ElCard>

    <!-- 入库单弹窗 -->
    <WmsReceiptOrderDialog
      v-model:visible="dialogVisible"
      :type="dialogType"
      :order-data="currentOrderData"
      @submit="handleDialogSubmit"
    />

    <!-- 批量处理弹窗 -->
    <WmsBatchProcessDialog
      v-model:visible="batchProcessDialogVisible"
      :selected-rows="selectedRows"
      order-type="receipt"
      @submit="handleBatchProcessSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { useTable } from "@/composables/useTable";
import { WmsReceiptOrderService } from "@/api/wms/orderApi";
import { useWmsStore } from "@/store/modules/wms";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Operation,
  Download,
  Printer,
  View,
  Edit,
  Check,
  Delete,
} from "@element-plus/icons-vue";

// 导入子组件
import WmsReceiptOrderSearch from "./components/WmsReceiptOrderSearch.vue";
import WmsReceiptOrderDialog from "./components/WmsReceiptOrderDialog.vue";
import WmsReceiptOrderDetail from "./components/WmsReceiptOrderDetail.vue";
import WmsBatchProcessDialog from "../components/WmsBatchProcessDialog.vue";

defineOptions({ name: "WmsReceiptOrder" });

const wmsStore = useWmsStore();

// 表格配置
const {
  tableData,
  columns,
  columnChecks,
  isLoading,
  paginationState,
  searchFilter,
  onPageSizeChange,
  onCurrentPageChange,
  refreshData,
  handleSearch,
  handleReset,
} = useTable<WMS.Order.ReceiptOrderInfo>({
  core: {
    apiFn: WmsReceiptOrderService.getReceiptOrderList,
    apiParams: {
      current: 1,
      size: 20,
    },
    columnsFactory: () => [
      {
        type: "selection",
        width: 50,
      },
      {
        type: "expand",
        width: 50,
      },
      {
        prop: "orderInfo",
        label: "单据信息",
        slot: "orderInfo",
        minWidth: 180,
        fixed: "left",
      },
      {
        prop: "warehouseInfo",
        label: "仓库/库区",
        slot: "warehouseInfo",
        minWidth: 150,
      },
      {
        prop: "merchantInfo",
        label: "商户",
        slot: "merchantInfo",
        width: 120,
      },
      {
        prop: "statusInfo",
        label: "状态",
        slot: "statusInfo",
        width: 100,
        align: "center",
      },
      {
        prop: "amountInfo",
        label: "金额/数量",
        slot: "amountInfo",
        width: 150,
        align: "center",
      },
      {
        prop: "createTime",
        label: "创建时间",
        width: 180,
        formatter: (row) => row.createTime || "-",
      },
      {
        prop: "actions",
        label: "操作",
        width: 200,
        slot: "actions",
        fixed: "right",
      },
    ],
  },
});

// 弹窗状态
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit" | "view">("add");
const currentOrderData = ref<WMS.Order.ReceiptOrderInfo | null>(null);
const batchProcessDialogVisible = ref(false);

// 选中的行
const selectedRows = ref<WMS.Order.ReceiptOrderInfo[]>([]);

// 明细加载状态
const detailLoadingMap = ref<Record<number, boolean>>({});

// 处理选择变化
const handleSelectionChange = (selection: WMS.Order.ReceiptOrderInfo[]) => {
  selectedRows.value = selection;
};

// 处理展开变化
const handleExpandChange = (
  row: WMS.Order.ReceiptOrderInfo,
  expanded: boolean,
) => {
  if (expanded) {
    detailLoadingMap.value[row.id] = true;
  }
};

// 处理明细加载完成
const handleDetailLoaded = (orderId: number) => {
  detailLoadingMap.value[orderId] = false;
};

// 显示弹窗
const showDialog = (
  type: "add" | "edit" | "view",
  orderData?: WMS.Order.ReceiptOrderInfo,
) => {
  dialogType.value = type;
  currentOrderData.value = orderData || null;
  dialogVisible.value = true;
};

// 查看订单
const handleView = (row: WMS.Order.ReceiptOrderInfo) => {
  showDialog("view", row);
};

// 编辑订单
const handleEdit = (row: WMS.Order.ReceiptOrderInfo) => {
  showDialog("edit", row);
};

// 处理订单
const handleProcess = async (row: WMS.Order.ReceiptOrderInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要处理入库单"${row.receiptOrderNo}"吗？`,
      "处理确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    await WmsReceiptOrderService.processReceiptOrder(row.id);
    ElMessage.success("处理成功");
    refreshData();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("处理失败");
    }
  }
};

// 删除订单
const handleDelete = async (row: WMS.Order.ReceiptOrderInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除入库单"${row.receiptOrderNo}"吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    await WmsReceiptOrderService.deleteReceiptOrder(row.id);
    ElMessage.success("删除成功");
    refreshData();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 批量处理
const handleBatchProcess = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要处理的订单");
    return;
  }
  batchProcessDialogVisible.value = true;
};

// 导出数据
const handleExport = async () => {
  try {
    const response = await WmsReceiptOrderService.exportReceiptOrderData(
      searchFilter.value,
    );
    // 处理文件下载
    const url = window.URL.createObjectURL(response);
    const link = document.createElement("a");
    link.href = url;
    link.download = `入库单数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success("导出成功");
  } catch (error) {
    ElMessage.error("导出失败");
  }
};

// 打印
const handlePrint = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要打印的订单");
    return;
  }
  // 打印逻辑
  ElMessage.info("打印功能开发中...");
};

// 处理弹窗提交
const handleDialogSubmit = () => {
  dialogVisible.value = false;
  refreshData();
};

// 处理批量处理弹窗提交
const handleBatchProcessSubmit = () => {
  batchProcessDialogVisible.value = false;
  refreshData();
};

// 工具方法
const getOrderTypeTagType = (type: number) => {
  const typeMap: Record<number, string> = {
    1: "primary",
    2: "success",
    3: "warning",
  };
  return typeMap[type] || "info";
};

const getOrderTypeName = (type: number) => {
  const typeMap: Record<number, string> = {
    1: "采购入库",
    2: "退货入库",
    3: "调拨入库",
  };
  return typeMap[type] || "未知";
};

const getStatusTagType = (status: number) => {
  const statusMap: Record<number, string> = {
    1: "info",
    2: "warning",
    3: "success",
    4: "danger",
  };
  return statusMap[status] || "info";
};

const getStatusName = (status: number) => {
  const statusMap: Record<number, string> = {
    1: "待处理",
    2: "处理中",
    3: "已完成",
    4: "已取消",
  };
  return statusMap[status] || "未知";
};

const canEdit = (row: WMS.Order.ReceiptOrderInfo) => {
  return row.receiptOrderStatus === 1; // 只有待处理状态可以编辑
};

const canProcess = (row: WMS.Order.ReceiptOrderInfo) => {
  return row.receiptOrderStatus === 1 || row.receiptOrderStatus === 2; // 待处理或处理中可以处理
};

const canDelete = (row: WMS.Order.ReceiptOrderInfo) => {
  return row.receiptOrderStatus === 1; // 只有待处理状态可以删除
};
</script>

<style lang="scss" scoped>
.wms-receipt-order-page {
  .order-info {
    .order-no {
      font-weight: 500;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }

    .order-type {
      margin-top: 4px;
    }
  }

  .warehouse-info {
    .warehouse-name {
      font-weight: 500;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }

    .area-name {
      font-size: 12px;
      color: var(--el-text-color-regular);
    }
  }

  .amount-info {
    .total-amount {
      margin-bottom: 4px;
    }

    .item-count {
      text-align: center;
    }
  }

  .text-placeholder {
    color: var(--el-text-color-placeholder);
  }
}
</style>
